package p02_queue;

/**
 * 队列
 */
public class ArrayQueue {
    private int maxSize;
    private int front;
    private int rear;
    private int[] arr;

    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.front = -1;
        this.rear = -1;
        this.arr = new int[this.maxSize];
    }

    /**
     * 判断队列是否满了。
     *
     * @return
     */
    public boolean isFull() {
        return rear == maxSize - 1;
    }

    /**
     * 判断队列是否为空。
     *
     * @return
     */
    public boolean isEmpty() {
        return rear == front;
    }

    /**
     * 向队列添加元素
     *
     * @param n 待添加的元素
     */
    public void add(int n) {
        if (isFull()) {
            System.out.println("队列已满！");
        } else {
            rear++;
            arr[rear] = n;
        }
    }

    /**
     * 从队列中获取元素
     *
     * @return
     */
    public int get() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空！");
        } else {
            front++;
            return arr[front];
        }
    }

    /**
     * 将整个队列打印到console。
     */
    public void show() {
        if (isEmpty()) {
            System.out.println("队列为空！");
        } else {
            for (int i = front + 1; i < size(); i++) {
                System.out.printf("[%d] : %d\n", i - front - 1, arr[i]);
            }
        }
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空！");
        } else {
            return arr[front + 1];
        }
    }

    public int size() {
        return rear - front;
    }
}
